<template>
  <div class="container" v-loading="loading">
    <div class="content content-left">
      <div class="tabs">
        <div class="tab" :class="{ active: moduleActive === item.id }" @click="moduleActive = item.id" v-for="item in moduleList" :key="item.id">{{ item.name }}</div>
      </div>
      <div class="tab-contents" ref="tabContent">
        <div class="tab-content" :style="{ transform: `scale(${scale})` }" :class="{ active: moduleActive === 1 }">
          <DomToImage ref="DomToImage1" id="DomToImage1" :title="form.title" @done="createImageDone">
            <PosterModule1 :formData="form" id="DomToImage1" />
          </DomToImage>
        </div>
        <div class="tab-content" :style="{ transform: `scale(${scale})` }" :class="{ active: moduleActive === 2 }">
          <DomToImage ref="DomToImage2" id="DomToImage2" :title="form.title" @done="createImageDone">
            <PosterModule2 :formData="form" id="DomToImage2" />
          </DomToImage>
        </div>
      </div>
    </div>
    <div class="content content-right">
      <p class="title">处置信息</p>
      <PushDetailLeft @getdetail="handleGetDetail" show-module="info" :sts-list="stsList" :id="id"></PushDetailLeft>
      <p class="title">海报内容</p>
      <el-form size="mini" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item prop="title" label="标题">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item prop="num" label="数量">
          <el-input v-model="form.num" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item prop="address" label="地区">
          <el-cascader v-model="form.address" :options="options" :props="props" clearable></el-cascader>
        </el-form-item>
        <el-form-item prop="img" label="图片">
          <el-upload :http-request="handleUpload1" class="avatar-uploader" action="" :show-file-list="false" accept="image/jpeg, image/png" :before-upload="beforeUpload" :on-preview="handlePreview" :on-remove="handleRemove" :limit="1" :file-list="imagesFileList">
            <img v-if="form.images" :src="form.images" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">支持上传jpg，png格式图片，最大不超过10MB</div>
          </el-upload>
          <el-button size="mini" type="primary" plain class="btn-cropper" @click="showCropper = true">剪裁图片</el-button>
        </el-form-item>
        <el-form-item prop="code" label="二维码">
          <el-upload :http-request="handleUpload2" class="avatar-uploader" action="" :show-file-list="false" accept="image/jpeg, image/png" :before-upload="beforeUpload" :on-preview="handlePreview" :on-remove="handleRemove" :limit="1" :file-list="codeFileList">
            <img v-if="form.code" :src="form.code" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">支持上传jpg，png格式图片，最大不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-button size="mini" @click="onCancel">取消</el-button>
          <el-button size="mini" type="primary" @click="onSubmit">生成</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--  图片剪裁-->
    <el-dialog title="图片剪裁" :close-on-click-modal="false" :append-to-body="true" :visible.sync="showCropper" width="50%">
      <PosterCropper @close="showCropper = false" @submit="handleCropperDone" v-if="showCropper" :url="form.images"></PosterCropper>
    </el-dialog>
  </div>
</template>
<script>
import PushDetailLeft from './PushDetailLeft'
import DomToImage from './DomToImage'
import PosterModule1 from './PosterModule1'
import PosterModule2 from './PosterModule2'
import PosterCropper from './PosterCropper'
import { formatDate } from '@/utils/index'

export default {
  props: {
    id: String,
    stsList: Array,
    options: Array,
  },
  components: { PushDetailLeft, DomToImage, PosterModule1, PosterModule2, PosterCropper },
  data() {
    return {
      showCropper: false,
      moduleList: [
        { id: 1, name: '模板1' },
        { id: 2, name: '模板2' },
      ],
      loading: false,
      pushList: [],
      form: {
        title: '',
        num: '',
        address: '',
        guzhi: '',
        images: [],
        code: '',
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        address: [{ required: true, message: '请选择地址', trigger: 'blur' }],
        images: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        code: [{ required: true, message: '请输入二维码', trigger: 'blur' }],
      },
      moduleActive: 1,
      imagesFileList: [],
      codeFileList: [],
      props: { value: 'name', label: 'name', checkStrictly: true },
      imageUrl: '',
      codeUrl: '',
      scale: 0.45,
    }
  },
  mounted() {
    this.handleResize()
    window.addEventListener('resize', this.handleResize)
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      const w = this.$refs.tabContent.offsetWidth
      this.scale = (w - 20) / 750
      if (this.scale > 0.45) {
        this.scale = 0.45
      }
      if (this.scale < 0.2) {
        this.scale = 0.2
      }
    },
    // 文件上传
    handleRemove(file) {
      this.form.images = []
    },
    handlePreview(file) {
      window.open(file.url)
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt10M
    },
    handleUpload1(file) {
      this.handleUpload('images', file)
    },
    handleUpload2(file) {
      this.handleUpload('code', file)
    },
    handleUpload(type, file) {
      this[type + 'FileList'] = []
      const that = this
      this.form[type] = file.file
      var reader = new FileReader()
      reader.readAsDataURL(file.file)
      reader.onloadend = function (e) {
        that.form[type] = e.target.result
        if (type === 'images') {
          setTimeout(() => {
            that.showCropper = true
          }, 500)
        }
      }
    },
    // 取消
    onCancel() {
      this.$emit('close')
    },
    // 生成
    onSubmit() {
      this.$refs.form.validate((flag) => {
        if (flag) {
          this.loading = true
          this.$refs['DomToImage' + this.moduleActive].createImage()
        }
      })
    },
    // 生成完成
    createImageDone() {
      this.loading = false
    },
    // 获取详情
    handleGetDetail(detail) {
      const that = this
      this.form.title = detail.title
      this.form.num = detail.num
      if (detail.address) {
        let address = detail.address.split(' ')
        this.form.address = address
      }
      this.form.guzhi = detail.guzhi
      if (detail.images) {
        // 使用示例
        this.imageToBase64(detail.images, function (base64) {
          that.form.images = base64
        })
      }
      this.form.time = formatDate(new Date(), 'Y/M/D')
    },
    // 剪裁完成
    handleCropperDone(data) {
      this.showCropper = false
      this.form.images = data
    },
    // 图片转base64
    imageToBase64(url, callback) {
      const xhr = new XMLHttpRequest()
      xhr.onload = function () {
        const reader = new FileReader()
        reader.onloadend = function () {
          callback(reader.result)
        }
        reader.readAsDataURL(xhr.response)
      }
      xhr.open('GET', url)
      xhr.responseType = 'blob'
      xhr.send()
    },
  },
}
</script>
<style scoped lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  height: 100%;
  .content {
    padding: 0 24px;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
    > .title {
      margin: 0 0 10px;
      font-weight: bold;
      font-size: 14px;
    }
    &.content-left {
      width: 35%;
    }
    &.content-right {
      width: 65%;
    }
  }
}

.push-list {
  font-size: 12px;
  .item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    .color {
      color: #409eff;
      cursor: pointer;
    }
    p {
      margin-top: 5px;
    }
  }
}
.avatar,
.avatar-uploader-icon {
  width: 80px !important;
  height: 80px !important;
  line-height: 80px;
}

.tabs {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .tab {
    cursor: pointer;
    padding: 0 20px;
    height: 30px;
    background: #efefef;
    margin-right: 10px;
    line-height: 30px;
    &.active {
      background: #409eff;
      color: #ffffff;
    }
  }
}
.tab-contents {
  height: 760px;
  overflow: hidden;
  padding: 10px;
}
.tab-content {
  display: none;
  margin-top: 10px;
  padding: 10px 0;
  width: 750px;
  height: 1624px;
  transform: scale(0.45);
  transform-origin: 0 0;
  &.active {
    display: block;
  }
}

.form-line {
  display: flex;
}
.el-upload__tip {
  margin-top: -5px;
  line-height: 1;
}
.btn-cropper {
  position: absolute;
  left: 100px;
  top: 54px;
}
</style>
